import subprocess

# 源ClickHouse服务器信息
source_host = "192.168.2.72"
source_port = 8123
source_database = "cust_label"
# 目标ClickHouse服务器信息
target_host = "192.168.3.5"
target_port = 8123  # 根据实际情况修改目标端口
target_database = "cust_label"  # 目标数据库名，可根据需求修改

# 假设clickhouse-dump.exe在C:\Program Files\ClickHouse\bin路径下，根据实际情况修改
clickhouse_dump_path = r"C:\Program Files\ClickHouse\bin\clickhouse-dump.exe"

# 构建导出命令
dump_command = [
    clickhouse_dump_path,
    "--host", source_host,
    "--port", str(source_port),
    "--database", source_database,
    "--format", "TabSeparatedWithNamesAndTypes"
]

# 构建导入命令
load_command = [
    clickhouse_dump_path,
    "--host", target_host,
    "--port", str(target_port),
    "--database", target_database,
    "--format", "TabSeparatedWithNamesAndTypes"
]

try:
    # 执行导出操作，并将输出传递给导入操作
    with subprocess.Popen(dump_command, stdout=subprocess.PIPE) as dump_process:
        with subprocess.Popen(load_command, stdin=dump_process.stdout) as load_process:
            dump_process.stdout.close()
            load_process.communicate()
    print("数据迁移成功！")
except subprocess.CalledProcessError as e:
    print(f"执行命令出错: {e}")
except Exception as ex:
    print(f"发生意外错误: {ex}")